#! /user/bin/env python
# coding:utf-8

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets
import datetime,time
import uuid
import sys
from data import *
from pycalendar import *

class QComboBox(QComboBox):

    def wheelEvent(self, QWheelEvent):
        pass


class QDateTimeEdit(QDateTimeEdit):

    def wheelEvent(self, QWheelEvent):
        pass

class Regist(QWidget):

    def __init__(self):
        super(Regist,self).__init__()
        self.setWindowTitle("登记")
        self.setFixedSize(360,500)
        self.setWindowFlags(Qt.WindowMinimizeButtonHint)
        self.center()
        self.db = DB()
        self.cur = self.db.cur
        self.register = 'hsqcdc'
        self.win = None
        self.set_ui()

    def set_ui(self):
        self.save_bnt = QPushButton("保存(F1)")
        self.save_bnt.clicked.connect(self.save_record)
        self.save_bnt.setStyleSheet("width:40px;height:30px;color:white;background-color:green;border:hidden;")
        self.new_bnt = QPushButton("添加(F2)")
        self.new_bnt.clicked.connect(self.new_record)
        self.new_bnt.setStyleSheet("width:40px;height:30px;color:white;background-color:brown;border:hidden;")
        self.close_bnt = QPushButton("关闭(ESC)")
        self.close_bnt.clicked.connect(self.close_win)
        self.close_bnt.setStyleSheet("width:40px;height:30px;color:white;background-color:red;border:hidden;")

        self.uuid = QLabel()
        self.uuid.setText(self.gen_uuid())

        self.regist_date_label = QLabel("登记日期")
        self.regist_date_label.setStyleSheet("width:60px;height:30px;color:black;background-color:None;border:hidden;")
        self.regist_date = QDateTimeEdit(QDateTime.currentDateTime())
        self.regist_date.setStyleSheet("width:60px;height:30px;color:black;background-color:white;border:hidden;")
        self.regist_date_bnt = QPushButton()
        self.regist_date_bnt.setStyleSheet("border:hidden;")
        self.regist_date_bnt.setIcon(QIcon('./img/cal.ico'))
        self.regist_date_bnt.clicked.connect(lambda:self.show_dt_cal(self.regist_date))
        self.name_label = QLabel("姓名")
        self.name = QLineEdit()
        self.name.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.id_label = QLabel("有效证件号码")
        self.id = QLineEdit()
        self.id.setPlaceholderText("身份证回车自动生成性别年龄")
        self.id.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.id.returnPressed.connect(self.id_check)
        self.gender_label = QLabel('性别')
        self.gender = QComboBox()
        self.gender.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.gender.addItem("男性")
        self.gender.addItem("女性")
        self.age_label = QLabel("年龄")
        self.age = QLineEdit()
        self.age.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.tel_label = QLabel("电话")
        self.tel = QLineEdit()
        self.tel.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.address_label = QLabel("住址")
        self.address= QLineEdit()
        self.address.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.occup_label = QLabel("职业")
        self.occup = QComboBox()
        occup_list = ['学生','教师','医务人员','冷链从业人员','幼托儿童','散居儿童','农民','干部职员','离退人员',
            '家务及待业','保姆','餐饮服务业','公共场所服务员','商业服务','工人','民工','牧民','渔船民','海员及长途驾驶员','不详','其他']
        for i in occup_list:
            self.occup.addItem(i)
        self.occup.setEditable(True)
        self.occup.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.company_label = QLabel("工作单位/学校")
        self.company = QLineEdit()
        self.company.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.serial_label = QLabel("病例编号")
        self.serial= QLineEdit()
        self.serial.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.backup_label = QLabel("备注")
        self.backup = QLineEdit()
        self.backup.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        self.status_label = QLabel("目前状态")
        self.status = QComboBox()
        self.status.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        test_list = ['健康人群','一般接触者','密接','初筛阳性','疑似病例','无症状感染者','确诊','康复']
        for i in test_list:
            self.status.addItem(i)
        self.status.setEditable(True)
        self.measure_label = QLabel("目前管理")
        self.measure = QComboBox()
        self.measure.setStyleSheet("width:60px;height:40px;color:black;background-color:white;border:hidden;")
        test_list2 = ['无措施','居家监测','集中隔离','定点医院']
        for i in test_list2:
            self.measure.addItem(i)
        self.measure.setEditable(True)

        self.bnt_layout = QHBoxLayout()
        self.bnt_layout2 = QWidget()
        self.bnt_layout.addWidget(self.close_bnt)
        self.bnt_layout.addWidget(self.new_bnt)
        # self.bnt_layout.addWidget(self.update_bnt)
        self.bnt_layout.addWidget(self.save_bnt)
        self.bnt_layout2.setLayout(self.bnt_layout)

        self.info_layout = QGridLayout()
        self.info_layout2 = QWidget()
        widget_list = [self.regist_date_label,self.regist_date,
                    self.name_label,self.name,self.id_label,self.id,self.gender_label,self.gender,
                    self.age_label,self.age,self.tel_label,self.tel,self.address_label,self.address,
                    self.occup_label,self.occup,self.company_label,self.company,
                    self.status_label,self.status,
                    self.measure_label,self.measure,self.serial_label,self.serial,self.backup_label,self.backup]
        for i in range(12):
            self.info_layout.addWidget(widget_list[i*2],i,0)
            self.info_layout.addWidget(widget_list[i*2+1],i,1)
        self.info_layout.addWidget(self.regist_date_bnt,0,2)

        self.info_layout2.setLayout(self.info_layout)

        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(self.info_layout2)
        self.main_layout.addWidget(self.bnt_layout2)
        self.main_layout.addWidget(self.uuid)
        self.setLayout(self.main_layout)


    def save_record(self):
        if self.name.text() and self.id.text():
            try:
                age = int(self.age.text())
            except:
                age = 0
            data_dic = {
                'name':self.name.text(),
                'id':self.id.text().upper(),
                'gender':self.gender.currentText(),
                'age':age,
                'tel':self.tel.text(),
                'address':self.address.text(),
                'occup':self.occup.currentText(),
                'company':self.company.text(),
                'present_status':self.status.currentText(),
                'present_measure':self.measure.currentText(),
                'backup':self.backup.text(),
                'uuid':self.id.text().upper(),
                'date':self.change_datetime(self.regist_date),
                'register':self.register,
                'serial':self.serial.text()
            }
            if self.save_bnt.text() == '保存(F1)':
                self.save_bnt.setText('更新')
            # try:
                person_sql = ''' insert into person values ("{serial}","{uuid}",
                "{name}","{id}","{gender}",{age},"{tel}",'{address}',
                "{occup}","{company}",{date},"{present_status}","{present_measure}",
                '{backup}',"{register}",0
                )
                '''.format(**data_dic)
                # self.cur.execute(person_sql)
            else:
            # except:
                person_sql = ''' update person set serial = "{serial}", name =
                "{name}",id = "{id}",gender = "{gender}", age = {age},
                tel= "{tel}",address = '{address}',
                occup = "{occup}",company = "{company}",backup= '{backup}',regist_date = {date},
                present_status = "{present_status}", present_measure =
                "{present_measure}" where uuid = "{uuid}"
                '''.format(**data_dic)
            self.cur.execute(person_sql)
            self.db.con.commit()
        else:
            self.messagebox_auto_close("请输入姓名身份证")

    def new_record(self):
        # widget_list = [self.name,self.id,self.gender,
        #     self.age,self.tel,self.address,
        #     self.gps,self.status,self.measure,self.backup]
        # for i in widget_list:
        #     i.clear()
        # self.uuid.setText(self.gen_uuid())
        # self.save_bnt.setText('保存(F1)')
        self.close()
        if self.win:
            self.win.close()
        self.win = Regist()
        self.win.show()

    def show_dt_cal(self, tmp):#含时间日历控件
        self.cal = Calendar_With_Clock(tmp)
        self.cal.show()
        self.cal.datetime_signal.connect(self.input_deathday)

    def input_deathday(self, list):
        list[0].setDateTime(list[1])

    def change_datetime(self,pyqtdatetime):   # a pyqtdate style /yyyymmdd to time stamp
        pydate = pyqtdatetime.dateTime().toPyDateTime()
        base_date = datetime.datetime(1970,1,1,0,0)
        day_delta = pydate - base_date
        days = day_delta.days
        seconds = day_delta.seconds
        seconds += days*24*3600
        return seconds

    def close_win(self):
        self.db.con.close()
        self.close()

    def gen_uuid(self):
        return (str(uuid.uuid1()))

    def id_check(self):
        id_upper = self.id.text().upper().strip()
        sql = '''select * from person where id = "{}"
        '''.format(id_upper)
        self.cur.execute(sql)
        check_rslt = self.cur.fetchone()
        if check_rslt:
            msg = QMessageBox.information(self,'tips','有相同证件,是否更新原纪录YES或重新登记NO',QMessageBox.Yes,QMessageBox.No)
            if msg == QMessageBox.Yes:
                self.uuid.setText(check_rslt[1])
            else:
                self.uuid.setText(self.gen_uuid())
            self.name.setText(check_rslt[2])
            self.tel.setText(check_rslt[6])
            self.address.setText(check_rslt[7])
            self.occup.setCurrentText(check_rslt[8])
            self.company.setText(check_rslt[9])
            self.regist_date.setDateTime(self.to_pydatetime(check_rslt[10]))
            self.status.setCurrentText(check_rslt[11])
            self.measure.setCurrentText(check_rslt[12])
            self.backup.setText(check_rslt[13])

        if len(id_upper) == 18:
            try:
                certify_number = ['1','0','X','9','8','7','6','5','4','3','2']
                std_number = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
                sum = 0
                for i in range(17):
                    sum += int(id_upper[i])*std_number[i]
                certify_rslt = certify_number[sum%11]
                if certify_rslt == id_upper[-1]:
                    self.id.setText(id_upper)
                    year2 = int(id_upper[6:10])
                    month2 = int(id_upper[10:12])
                    day2 = int(id_upper[12:14])
                    now = (datetime.datetime.now() + datetime.timedelta(days=1))
                    year = now.year
                    month = now.month
                    day = now.day
                    if year == year2:
                        self.age.setText('1')
                    else:
                        if month > month2 or (month == month2 and day > day2 ):
                            self.age.setText(str(year-year2))
                        else:
                            self.age.setText(str(year-year2-1))

                    sex = int(id_upper[-2])
                    if sex%2==0:
                        self.gender.setCurrentIndex(1)
                    else:
                        self.gender.setCurrentIndex(0)
                    self.tel.setFocus()
                    self.id.setStyleSheet('color:black;')
                else:
                    self.id.setStyleSheet('color:red;')
                    # QMessageBox.information(self,'提示','身份证号码不正确',QMessageBox.Yes, QMessageBox.Yes)
            except:
                self.id.setStyleSheet('color:red;')
        else:
            self.id.setStyleSheet('color:red;')
            # QMessageBox.information(self,'提示','身份证号码不满18位',QMessageBox.Yes, QMessageBox.Yes)
        self.tel.setFocus()

    def center(self):
        self.screen = QDesktopWidget().screenGeometry()
        self.size = self.geometry()
        self.move(int((self.screen.width()-self.size.width())/2),
                 int((self.screen.height()-self.size.height())/2)
                  )

    def to_pydatetime(self, a):
        b = datetime.datetime(1970, 1, 1, 0, 0) + datetime.timedelta(seconds=a)
        return QDateTime(b.year, b.month, b.day, b.hour, b.minute)

    def keyPressEvent(self,e):
        if e.key() == Qt.Key_Escape:
            self.close_win()
        if e.key() == Qt.Key_F1:
            self.save_record()
        if e.key() == Qt.Key_F2:
            self.new_record()

    def messagebox_auto_close(self,txt = '完成!!!',time =1):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setWindowTitle("# WARNING: ")
        msg.setText(txt)
        msg.setStandardButtons(QMessageBox.Yes)
        msg.button(QMessageBox.Yes).animateClick(time*1000)
        msg.exec_()
